<?

if(!$_SESSION['sid'])
    exit('请登录');
include_once '/var/www/html/new/com.inc.php';
$ac=$GLOBALS['_ac'];
$pw=$GLOBALS['_pw'];
$s = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));
$aid=$_SESSION['sid'];
$lids=$_REQUEST['type']? $_REQUEST['type']:'';
switch ($_POST['ztime']) {
	case '1':
        $btime=date('Y-m-d',strtotime("-7days"));
		break;
    case '2':
        $btime=date('Y-m-d',strtotime("-30days"));
        break;
    case '3':
        $btime=date('Y-m-d',strtotime("-90days"));
        break;
    case '4':
        if((strtotime($_POST['bt'])-$_SERVER['REQUEST_TIME'])>90*3600*24)//超过90天报错
            exit ("<script>
                            alert('所选时间间隔不能大于三个月');
                            history.go(-1);
                        </script>");
        $btime=$_POST['bt'];
        break;
	default:
        $btime=date('Y-m-d',strtotime("-7days"));
		break;
}

$etime=$_POST['et']? $_POST['et']:date('Y-m-d');
$bt = $btime .' 00:00:00';
$et = $etime .' 23:59:59'; 
$lid_arr=array();
$x_ob1 = simplexml_load_string(
    $s -> Order_Globle_Search(
     "","$aid", "", "", "", "", "", "", "", "",
     "", "", "", "", "", "1", "", "", "", "",
     "0", "100", "0", "0","","0","0", "0","","",
      "", "", "", "", ""
    )
);
foreach($x_ob1->Rec as $key1=>$val1){
  if($v->UUmid==$v->UUaid)//自供自销
    $lid_arr[(int)$val1->UUlid]=(string)$val1->UUltitle;
}
$x_ob2 = simplexml_load_string(
  $s -> Order_Globle_Search(
     "","", "", "", "", "", "", "", "", "",
     "$bt", "$et", "", "", "", "1", "", "", "", "",
     "0", "100", "0", "0","","0","0", "0","","",
      "$aid", "", "", "", "")
);
//print_r($x_ob2);
foreach($x_ob2->Rec as $key2=>$val2){
    $lid_arr[(int)$val2->UUlid]=(string)$val2->UUltitle;
}
$lid_arr=array_unique($lid_arr);
//模糊搜索产品名
if($_POST['action'] == 'land_search'){
    if(!$_POST['ltitle'])
        exit('{"error":"未输入有效名称"}');
    $json_lid = array();
    $n=0;
    foreach($lid_arr as $key => $val){
        if(strpos($val,$_POST['ltitle'])!== false){
            if($n==9) break;
            ++$n;
            $json_lid[] = array('id'=>$key,'ltitle'=>$val);
        }
    }
    exit(json_encode(array('sta'=>'suc','list'=>$json_lid)));
}
$lid = $_POST['title'] ? intval($_POST['title']) : '';
if($lid != ''){
    $sql = "select title from uu_land where id=$lid";
    $GLOBALS['le']->query($sql);
    $GLOBALS['le']->fetch_assoc();
    $sth = $GLOBALS['le']->f('title');
}

 for($date = $btime;$date <= $etime;$date = date('Y-m-d',strtotime($date)+86400))
	{
        $st = $date .' 00:00:00';
        $et = $date .' 23:59:59';
        $x2 = simplexml_load_string(
        $s -> Order_Globle_Search(
             "","$aid", "$lid", "", "", "", "", "", "", "",
             "$st", "$et", "", "", "", "", "", "", "", "",
             "0", "1800", "0", "0","","0","0", "0","","",
              "", "", "", "", ""
            )
        );
	  //$selft=0;
	  foreach($x2->Rec as $k=>$v)
	  { 
	    $vb=(int)$v->UUpmode;
          if($v->UUmid==$v->UUaid)//自供自销
		    $selft+=(int)$v->UUtnum;
	  }
	  //echo $var;
	   $titname = simplexml_load_string(
           $s -> Order_Globle_Search(
             "","", "$lid", "", "", "", "", "", "", "",
             "$st", "$et", "", "", "", "", "", "", "", "",
             "0", "800", "0", "0","","0","0", "0","","",
              "$aid", "", "", "", ""
           )
       );
	  //根据购买者类型进行累加
	  foreach($titname->Rec as $key=>$v){
          if((string)$v->UUaids!='0'){
              $UUmid = (int)$v->UUbuyid;
          }else{
              $UUmid = (int)$v->UUmid;
              $mer_arr[$UUmid]['dname'] = (string)$v->UUdname;//如果是最末级分销商 直接从订单里取名字
          }
          $mer_arr[$UUmid]['tnum']+=(int)$v->UUtnum;
          $mer_arr[$UUmid]['UUmid'] = $UUmid;
      }
          /* !!旧的统计各个分销商是哪种类型的
		  $c_type="select fid,com_type from pft_member_extinfo where fid=$val->UUmid";
		  $GLOBALS['le']->query($c_type);
          while($typerow=$GLOBALS['le']->fetch_assoc())
		  {
             switch($typerow['com_type']){
                   case "团购": $teamt+=(int)$val->UUtnum;break;//暂未加入
                   case "旅行社": $lvt+=(int)$val->UUtnum;break;
                   case "淘宝/天猫": $taot+=(int)$val->UUtnum;break;
                   case "景区": $selft+=(int)$val->UUtnum;break;//景区、酒店归为自销；
                   case "酒店": $selft+=(int)$val->UUtnum;break;
                   case "加盟门店": $joint+=(int)$val->UUtnum;break;
                   case "电商": $dtt+=(int)$val->UUtnum;break;
                   default : $otht+=(int)$val->UUtnum;break;//除以上之外归为其他；
                   }
		  
          }
	  }
	  */
  }
/*  !!旧的统计各个分销商是哪种类型的
//取大于0的票数
$team_arr['团购']=$teamt>0? $teamt:'';
$lvt_arr['旅行社']=$lvt>0? $lvt:'';
$taot_arr['淘宝/天猫']=$taot>0? $taot:'';
$selft_arr['自销']=$selft>0? $selft:'';
$joint_arr['加盟门店']=$joint>0? $joint:'';
$dtt_arr['电商']=$dtt>0? $dtt:'';
$otht_arr['其他']=$otht>0? $otht:'';

//合并数据输出所需字符串格式
$mer_arr=array_merge($team_arr,$lvt_arr,$taot_arr,$selft_arr,$dtt_arr,$otht_arr,$joint_arr);
foreach($mer_arr as $names=>$tict)
{
	if($tict>0)
	{
		$tictstr.="{value:".$tict.", "."name:"."'".$names."'"."},";
	
    }
}
*/

if(count($mer_arr)>10){
    foreach($mer_arr as $k => $v){
        $sort[] = $v['tnum'];
    }
    array_multisort($sort,SORT_DESC,$mer_arr);
}
$n = 0;
foreach($mer_arr as $k => $v){
    ++$n;
    if(!$v['dname']){
        $sql = "select dname from pft_member where id={$v['UUmid']} limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $v['dname'] = $GLOBALS['le']->f('dname');
    }
    if($n<10){
        $dname_arr .= "'". $v['dname']."',";
        $tictstr.="{value:".$v['tnum'].", "."name:"."'".$v['dname']."'"."},";
    }elseif($n==10){
        $dname_arr .= "'其他'";
        $tictstr_else += $v['tnum'];
    }else{
        $tictstr_else += $v['tnum'];
    }
}
$tictstr = $tictstr_else ? $tictstr."{value:".$tictstr_else.", "."name:"."'"."其他"."'"."}" :$tictstr;
$tictstr=rtrim($tictstr,',');
$dname_arr=rtrim($dname_arr,',');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
	<link rel="stylesheet" type="text/css" href="http://www.12301.cc/css/ui/zpie.css">
	<script language="javascript" src="http://www.12301.cc/js/jquery-1.8.0.min.js"></script>
<!-- 	<script language="javascript" src="http://www.12301.cc/js/ui/zpie.js"></script> -->
</head>
<body>
	<form action="http://www.12301.cc/tpl/zpie2.html" method="post" id="ti" name="form" >
        <input type="hidden" name="ztime" id="ztime" value="<?=$_POST['ztime']?>">
        <input type="hidden" name="title" id="title" value="<?=$_POST['title']?>">
		<div class="order_all">
			<span class="order_ca">销售渠道分布</span> 
			<span class="order_cb">产品</span>
			<input type="text" class="suggest_input"  autocomplete="off" id="land_a" value="<?=$sth?>">
			<i class="iconfont select_icon">&#xe600;</i>
			<ul class="suggest_ul" style="display: none;"></ul>
		</div>
		<div class="time_select">
			<ul class="time_ul">
				<li  class="time_li weeka  <?=$_POST['ztime']==1?'active':''?>">一周</li>
				<li  class="time_li moutha <?=$_POST['ztime']==2?'active':''?>">一月</li>
				<li  class="time_li springa <?=$_POST['ztime']==3?'active':''?>">一季度</li>
				<li  class="time_li wangt <?=$_POST['ztime']==4?'active':''?>">自定义</li>
			</ul>
			<div class="time_show">
				<span><?=$btime?></span>至 <span><?=$etime?></span>
			</div>
			<div class="time_none">
				<input type="text" data-t="bt" id="txtStartTime_c" value="<?=$btime?>" name="bt" data-msg="请选择时间段" class="textInp w175 alliNameInp" autocomplete="off"/> 至 
				<input type="text" data-t="et" id="txtEndTime_c" value="<?=$etime?>" name="et" data-msg="请选择时间段" class="textInp w175 alliNameInp" autocomplete="off"/>
				<input type="submit" id="sub" value="确定">
			</div>
		</div>
		
	
	</form>
    <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
    <div id="main" style="height:400px;width:800px"></div>
    <!-- ECharts单文件引入 -->
    <script language="javascript" src="//www.12301.cc/js/echarts-2.2.0/build/dist/echarts.js"></script>
	<script language="javascript" src="http://www.12301.cc/js/WdatePicker.js"></script>
	<script language="javascript" src="http://www.12301.cc/js/jquery-1.8.0.min.js"></script>
	<script src="http://www.12301.cc/js/select2.js"></script>
	<link rel="stylesheet" type="text/css" href="http://www.12301.cc/css/select2.css">
    <script type="text/javascript">
        // 路径配置
        require.config({
            paths: {
                echarts: '//www.12301.cc/js/echarts-2.2.0/build/dist'
            }
        });
        
        // 使用
        require(
            [
                'echarts',
                'echarts/chart/pie'
            ],
            function (ec) {
                // 基于准备好的dom，初始化echarts图表
                var myChart = ec.init(document.getElementById('main')); 
                
                var option = {
    title : {
        text: '产品销售渠道分布',
       
        x:'center'
    },
    tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        show:true<?//=$n>9?'false':'true'?>,
        orient : 'vertical',
        x : 'left',
        data:[<?=$dname_arr?>],
        textStyle:{
                color: 'blue'
        }
    },
    toolbox: {
        show : false,//数据,刷新,保存图片
        feature : {
           
            dataView : {show: true, readOnly: false},
            magicType : {
                show: false, 
                type: ['pie', 'funnel'],
                option: {
                    funnel: {
                        x: '25%',
                        width: '50%',
                        funnelAlign: 'left',
                        max: 1548
                    }
                }
            },
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    calculable : true,
    series : [
        {
            name:'销售渠道',
            type:'pie',
            radius : '55%',
            startAngle:-90,
            center: ['50%', '60%'],
            data:[
                <?=$tictstr;?>
            ],
            legendHoverLink:false
        }
    ]
};
                // 为echarts对象加载数据 
                myChart.setOption(option); 
            }
        );
		
		
	$("#bindList").select2({
				placeholder: "Select a State",
				allowClear: true
    });

    $("#s2id_bindList").css('width','300px');

   
	$(".weeka").click(function(){
		$("#ztime").val("1");
		$(".wangt").removeClass("active");
		$("#ti").submit();
	})
	$(".moutha").click(function(){
		$("#ztime").val("2");
		$(".wangt").removeClass("active");
		$(".time_show_a").css("display","none");
		$("#ti").submit();
	})
	$(".springa").click(function(){
		$("#ztime").val("3");
		$(".wangt").removeClass("active");
		$("#ti").submit();
		
	})
	$(".wangt").click(function(){
	    $(this).addClass("active");
		$(".weeka").removeClass("active");
		$(".moutha").removeClass("active");
		$(".springa").removeClass("active");
		$(".time_show").css("display","none");
		$(".time_none").css("display","block");
	})
	$("#sub").click(function(){
		$("#ztime").val("4");
	})
	$(document).ready(function(){ 
		if($("#ztime").val()=="4"){
		$(".time_none").css("display","block");
		}
		})
	$("#txtStartTime_c").bind("click focus", function () {
       var endtimeTf = $dp.$('txtEndTime');
       WdatePicker({
           maxDate: '#F{$dp.$D(\'txtEndTime_c\')}',
           dateFmt: "yyyy-MM-dd",
           onpicked: function () { endtimeTf.focus(); }
            });
       });
    $("#txtEndTime_c").bind("click focus", function () {
            WdatePicker({
               minDate: '#F{$dp.$D(\'txtStartTime_c\')}',
               dateFmt: "yyyy-MM-dd"
           });
       });
	   
	  	$(".suggest_input").keyup(function(){
			if($(".suggest_input").val().length<=0){
				$(".liid").val("");
				$(".suggest_ul").hide(0);
				return; 
			}
			$.ajax({
			    "url" : "zpie2.html",
				"data" :  {action:'land_search',ltitle:$(".suggest_input").val()},
				"dataType":"json",
				"type": 'POST', 
				"success":function(data){
					$(".suggest_ul").show(0);
					var contents="";
					var list = data.list;
						for(var i in list){
						var id =list[i]["id"];
						var keywords =list[i]["ltitle"];
						contents=contents+"<li title="+keywords+" data-id="+id+" data-k="+keywords+">"+keywords+"</li>";
						}
						$(".suggest_ul").html(contents); 
					}          
			});
		  
	});  
	$(".suggest_ul").on("click","li",function(e){
				var target = $(e.currentTarget);
				var id = target.attr("data-id");
				var k = target.attr("data-k");
				$(".suggest_input").val(target.text());
				$("#title").val(id);
				$("#ti").submit();
				$(".suggest_ul").hide(0);
				
			})
    </script>
</body>
</html>